package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.PjCollection;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjSettlement;
import com.koron.css2.newProjectCenter.bean.query.PjCollectionQuery;
import com.koron.css2.newProjectCenter.mapper.PjCollectionMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjSettlementMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 工程报装-编制结算单条新增
 */
public class PjSettlemetInsert implements ServerInterface {
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjSettlement pjSettlement = JsonUtils.objectToPojo(req.getData(), PjSettlement.class);
            PjSettlementMapper pjSettlementMapper = factory.getMapper(PjSettlementMapper.class);
            PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
            PjCollectionMapper pjCollectionMapper = factory.getMapper(PjCollectionMapper.class);
            PjInfoBean pjInfoBean = pjInfoMapper.selectById(pjSettlement.getConsultId());
            PjCollectionQuery pjCollectionQuery = new PjCollectionQuery();
            pjCollectionQuery.setProjectCode(pjInfoBean.getBillNo());
            List<PjCollection> pjCollectionList = pjCollectionMapper.getList(pjCollectionQuery);
            for (PjCollection pjCollection : pjCollectionList) {
                if (!Objects.equals("END", pjCollection.getProcessState()) && !Objects.equals("CANCEL", pjCollection.getProcessState())){
                    return MessageBean.create(Constant.MESSAGE_INT_FAIL, "存在工程收款单未废弃或未收款", null);
                }
            }
            pjSettlement.setCreateInfo(userInfo);
            pjSettlement.setBillNo(Tools.getBillNo(factory,"pj_settlement"));
            pjSettlement.setBillDate(new Date());
            pjSettlementMapper.insert(pjSettlement);
            MessageBean<String> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"单条编制结算数据新增成功", String.class);
            messageBean.setData(pjSettlement.getId());
            return messageBean;
        } catch (Exception e) {
            logger.error("单条编制结算数据新增失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "单条编制结算数据新增失败", null);
        }
    }
}